package ruixinyi.experiment2.demos.web.dao;

import org.springframework.stereotype.Repository;
import ruixinyi.experiment2.demos.web.entity.Sys_role;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.transaction.Transactional;
import java.util.List;

@Repository
public class Sys_roleDaoImpl implements Sys_roleDao {

    // 使用EntityManager来执行更新操作
    @PersistenceContext
    private EntityManager entityManager;

    @Override
    @Transactional
    public Sys_role addSys_role(Sys_role sys_role) {
        return entityManager.merge(sys_role);
    }

    @Override
    public List<Sys_role> getAllSys_role() {
        // 使用EntityManager来获取所有角色信息
        return entityManager.createQuery("SELECT s FROM Sys_role s", Sys_role.class).getResultList();
    }

    @Override
    public Sys_role getSys_roleByid(Integer id) {
        // 使用EntityManager来根据ID获取角色信息
        return entityManager.find(Sys_role.class, id);
    }

    @Override
    @Transactional
    public int updateSys_role(Sys_role sys_role) {
        // 创建JPQL更新查询
        String query = "UPDATE Sys_role s SET s.name = :name, s.description = :description, s.create_time = :createTime, s.create_by = :createBy, s.update_time = :updateTime, s.update_by = :updateBy WHERE s.id = :id";
        Query q = entityManager.createQuery(query)
                .setParameter("name", sys_role.getName())
                .setParameter("description", sys_role.getDescription())
                .setParameter("createTime", sys_role.getCreate_time())
                .setParameter("createBy", sys_role.getCreate_by())
                .setParameter("updateTime", sys_role.getUpdate_time())
                .setParameter("updateBy", sys_role.getUpdate_by())
                .setParameter("id", sys_role.getId());
        return q.executeUpdate();
    }

    @Override
    @Transactional
    public int deleteSys_roleByid(Integer id) {
        // 创建JPQL删除查询
        String query = "DELETE FROM Sys_role s WHERE s.id = :id";
        Query q = entityManager.createQuery(query)
                .setParameter("id", id);
        return q.executeUpdate();
    }
}
